/*
 * @Author: 龙通印
 * @Date: 2020-09-01 10:34:26
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-12-16 17:15:31
 */

// 引入模块
const OSS = require('ali-oss');
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const package = require("../src/config")

var DeployType=process.argv.splice(2)[0]
// 使用永久密钥创建实例
var client = new OSS({
	region: package.oss.region,
	accessKeyId: package.oss.accessKeyId,
	accessKeySecret: package.oss.accessKeySecret,
	bucket: package.oss.bucket,
	timeout:10*60000
});

const isWindow = /^win/.test(process.platform)

let pre = path.resolve(__dirname, '../dist/')+ (isWindow ? '\\' : '')
const files = glob.sync(
    `${path.join(
      __dirname,
      '../dist/**/*.*'
    )}`
  )
pre = pre.replace(/\\/g, '/')
async function uploadFileCDN (files) {
    files.map(async file => {
        const key = getFileKey(pre, file)
        try {
            var res=await uploadFIle(key, file)
            console.log(`资源已上传至: ${res.url}`)
        } catch (err) {
            console.log('error', err)
        }
    })
}
async function uploadFIle (key, localFile) {
	return client.put(package.name+'/'+DeployType+'/'+key, localFile);
}
function getFileKey (pre, file) {
    if (file.indexOf(pre) > -1) {
      const key = file.split(pre)[1]
      return key.startsWith('/') ? key.substring(1) : key
    }
    return file
}

async function deleteOldFile(){
	var res=await client.list({prefix:package.name+'/'+DeployType})
	var task=[]
	if(res.objects&&Array.isArray(res.objects)){
		res.objects.forEach(item=>{
			task.push(client.delete(item.name))
		})
		return Promise.all(task)
	}
	return new Promise((res)=>res())

}

(async () => {
    if(DeployType=='test'){
		console.time('清除上一次的cdn文件')
		await deleteOldFile()
		console.timeEnd('清除上一次的cdn文件')
	}
    console.time('===开始上传文件===')
    await uploadFileCDN(files)

})()
